#include "wtk_wavfile.h"
void wtk_wavfile_close_fd(wtk_wavfile_t *f);

wtk_wavfile_t* wtk_wavfile_new(int sample_rate)
{
	wtk_wavfile_t *f;

	f=(wtk_wavfile_t*)wtk_calloc(1,sizeof(*f));
	wtk_wavfile_init(f,sample_rate);
	return f;
}

int wtk_wavfile_delete(wtk_wavfile_t *f)
{
	wtk_wavfile_clean(f);
	wtk_free(f);
	return 0;
}

void wtk_wavfile_init(wtk_wavfile_t *f,int sample_rate)
{
	f->file=0;
	f->max_pend=-1;
	f->pending=0;
	f->writed=0;
	wavehdr_init(&(f->hdr));
	wavehdr_set_fmt(&(f->hdr),1,sample_rate,2);
}

void wtk_wavfile_clean(wtk_wavfile_t *f)
{
	wtk_wavfile_close(f);
	//wtk_wavfile_close_fd(f);
}

void wtk_wavfile_close_fd(wtk_wavfile_t *f)
{
	if(f->file)
	{
		fclose(f->file);
		f->file=0;
	}
}

int wtk_wavfile_open(wtk_wavfile_t *f,char *fn)
{
	int ret=-1;

	f->pending=f->writed=0;
	wtk_wavfile_close_fd(f);
	wtk_mkdir_p(fn,'/',0);
	f->file=fopen(fn,"wb");
	if(!f->file){goto end;}
	ret=fwrite(&(f->hdr),sizeof(f->hdr),1,f->file);
	ret=ret==1?0:-1;
end:
	return ret;
}

int wtk_wavfile_write(wtk_wavfile_t *f,const char *data,int bytes)
{
	int ret;

	ret=fwrite(data,bytes,1,f->file);
	if(ret!=1){ret=-1;goto end;}
	f->writed+=bytes;
	f->pending+=bytes;
	if(f->max_pend>=0 && f->pending>f->max_pend)
	{
		ret=wtk_wavfile_flush(f);
	}else
	{
		ret=0;
	}
end:
	return ret;
}

int wtk_wavfile_flush(wtk_wavfile_t *f)
{
	int ret;

	ret=fseek(f->file,0,SEEK_SET);
	if(ret==-1){goto end;}
	wavehdr_set_size(&(f->hdr),f->writed);
	ret=fwrite(&(f->hdr),sizeof(f->hdr),1,f->file);
	if(ret!=1){ret=-1;goto end;}
	fflush(f->file);
	fseek(f->file,0,SEEK_END);
	f->pending=0;
	ret=0;
end:
	return ret;
}

int wtk_wavfile_close(wtk_wavfile_t *f)
{
	int ret;

	if(!f->file){ret=0;goto end;}
	ret=wtk_wavfile_flush(f);
	if(ret!=0){goto end;}
	wtk_wavfile_close_fd(f);
end:
	return ret;
}
